package com.czy.owner.ui.userinfo;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.czy.otherlib.wheelview.adapters.ArrayWheelAdapter;
import com.czy.otherlib.wheelview.widget.OnWheelScrollListener;
import com.czy.otherlib.wheelview.widget.WheelView;
import com.czy.owner.R;
import com.czy.owner.api.UpdateUserInfoApi;
import com.czy.owner.api.UserInfoApi;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.UpLoadUserPortraitModel;
import com.czy.owner.entity.UserInfoModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.api.BaseResultEntity;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.permission.Acp;
import com.czy.owner.permission.AcpListener;
import com.czy.owner.permission.AcpOptions;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.StringUtils;
import com.czy.owner.utils.TimeUtils;
import com.czy.owner.utils.glide.GlideUtils;
import com.czy.owner.utils.glide.config.GlideCacheConfig;
import com.czy.owner.widget.ActionSheetDialog;
import com.czy.owner.widget.RoundImageView;
import com.easemob.cases.MessageHelper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * Created by wangyang on 2017/5/9 0009.
 * 用户信息
 */

public class UserInfoActivity extends BaseActivity {
    @BindView(R.id.roundimgview)
    RoundImageView mRoundimgview;
    @BindView(R.id.tv_user_name_value)
    TextView tvUserNameValue;
    @BindView(R.id.tv_user_sex_value)
    TextView tvUserSexValue;
    @BindView(R.id.tv_user_phone_value)
    TextView tvUserPhoneValue;
    @BindView(R.id.tv_user_detail_adress_value)
    TextView tvUserDetailAdressValue;
    @BindView(R.id.tv_user_birthday)
    TextView tvUserBirthday;
    private static final int PHOTO_CARMERA = 1;
    private static final int PHOTO_PICK = 2;
    private static final int PHOTO_CUT = 3;
    public static final int USER_NAME = 4;
    public static final int USER_DETAIL_ADRESS = 5;
    private File tempFile = new File(Environment.getExternalStorageDirectory() + GlideCacheConfig.GLIDE_CARCH_DIR, getPhotoFileName());
    private ActionSheetDialog.SheetItemColor sheetItemColor;

    //    图片上传命名
    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss");
        return dateFormat.format(date) + ".jpg";
    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_userinfo;
    }

    @Override
    protected void initInjector() {
        getToolbarTitle().setText(R.string.user_info);
    }

    @Override
    protected void initViews() {
        Calendar c = Calendar.getInstance();
        currentYear = c.get(Calendar.YEAR);
        currentMonth = c.get(Calendar.MONTH) + 1;
        currentDay = c.get(Calendar.DAY_OF_MONTH);
        userInfoData();
    }

    @Override
    protected void updateViews() {

    }


    private void setUserInfo(UserInfoModel userInfoModel) {
        if (userInfoModel != null) {
            String userLogo = userInfoModel.getUserLogo();
            String userName = userInfoModel.getNickName();
            int sex = userInfoModel.getSex();
            String phone = userInfoModel.getPhone();
            String address = userInfoModel.getAddr();
            GlideUtils.loadImage(UserInfoActivity.this, userLogo, mRoundimgview, new GlideUtils.ImageLoadListener<String, GlideDrawable>() {
                @Override
                public void onLoadingComplete(String uri, ImageView view, GlideDrawable resource) {
                }

                @Override
                public void onLoadingError(String source, Exception e) {
                }
            }, R.mipmap.person_default_icon, R.mipmap.person_default_icon);
            tvUserNameValue.setText(userName);
            if (sex == 0) {
                tvUserSexValue.setText("女");
            } else if (sex == 1) {
                tvUserSexValue.setText("男");
            }
            tvUserPhoneValue.setText(phone);
            tvUserDetailAdressValue.setText(address);
            if (userInfoModel.getBirthday() != 0) {
                String formatDate = "yyyy-MM-dd";
                SimpleDateFormat dateFormat = new SimpleDateFormat(formatDate);
                String birthday = dateFormat.format(userInfoModel.getBirthday());
                tvUserBirthday.setText(birthday);
            } else {
                tvUserBirthday.setText("");
            }
        }

    }


    private void userInfoData() {
        UserInfoApi userInfoApi = new UserInfoApi(new HttpOnNextListener<UserInfoModel>() {
            @Override
            public void onNext(UserInfoModel model) {
                setUserInfo(model);
            }

            @Override
            public void onCacheNext(String cache) {
                super.onCacheNext(cache);

                Gson gson = new Gson();
                Type type = new TypeToken<BaseResultEntity<UserInfoModel>>() {
                }.getType();
                BaseResultEntity<UserInfoModel> userInfoCache = gson.fromJson(cache, type);
                setUserInfo(userInfoCache.getData());

            }


            @Override
            public void onError(Throwable e) {
                super.onError(e);
            }


        }, this);
        userInfoApi.setSession(UserHelper.getInstance().getSessionInfoModel(this).getSession());
        HttpManager manager = HttpManager.getInstance();
        manager.doHttpDeal(userInfoApi);

    }


    @OnClick(R.id.relative_user_portrait)
    public void userPortrait(View view) {
        new ActionSheetDialog(UserInfoActivity.this)
                .builder()
                .setCancelable(false)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("拍照", ActionSheetDialog.SheetItemColor.ThemeColor,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                if ((Build.VERSION.SDK_INT >= 23)) {
                                    onClickAllPermission();
                                } else {
                                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                    // 指定调用相机拍照后照片的储存路径
                                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
                                    startActivityForResult(intent, PHOTO_CARMERA);
                                }


                            }
                        })
                .addSheetItem("相册", ActionSheetDialog.SheetItemColor.ThemeColor,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                if ((Build.VERSION.SDK_INT >= 23)) {
                                    onClickWRITE();
                                } else {
                                    Intent intent = new Intent(Intent.ACTION_PICK, null);
                                    intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                                    startActivityForResult(intent, PHOTO_PICK);
                                }

                            }
                        }).show();
    }

    @OnClick(R.id.relative_user_name)
    public void userName(View view) {
        Intent ti = new Intent(UserInfoActivity.this, UpdateUserNameActivity.class);
        ti.putExtra("userInfoName", tvUserNameValue.getText().toString().trim());
        startActivityForResult(ti, USER_NAME);
    }

    @OnClick(R.id.relative_user_phone)
    public void userPhone(View view) {
        Intent ti = new Intent(UserInfoActivity.this, UpdateUserPhone.class);
        startActivity(ti);
    }

    @OnClick(R.id.relative_user_detail_adress)
    public void userDetailAdress(View view) {
        Intent ti = new Intent(UserInfoActivity.this, UpdateUserAdressActivity.class);
        ti.putExtra("userInfoAdress", tvUserDetailAdressValue.getText().toString().trim());
        startActivityForResult(ti, USER_DETAIL_ADRESS);
    }

    @OnClick(R.id.relative_user_birtchday)
    public void userBirtchday(View view) {
        showDateDialog();
    }

    @OnClick(R.id.relative_user_sex)
    public void userSex(View view) {
        sheetItemColor = ActionSheetDialog.SheetItemColor.ThemeColor;
        new ActionSheetDialog(UserInfoActivity.this)
                .builder()
                .setCancelable(false)
                .setCanceledOnTouchOutside(true)
                .addSheetItem(getResources().getString(R.string.user_man), sheetItemColor,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                tvUserSexValue.setText(getResources().getString(R.string.user_man));
                                UpdateUserInfoData("", "", "1", "", "");

                            }
                        })
                .addSheetItem(getResources().getString(R.string.user_woman), sheetItemColor,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                tvUserSexValue.setText(getResources().getString(R.string.user_woman));
                                UpdateUserInfoData("", "", "0", "", "");
                            }
                        }).show();

    }


    @OnClick(R.id.relative_user_birtchday)
    public void userBirthday(View view) {

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PHOTO_CARMERA:
                try {
                    if (tempFile != null) {
                        startPhotoZoom(Uri.fromFile(tempFile), 150);
                    }
                } catch (Exception e) {

                }

                break;
            case PHOTO_PICK:
                try {
                    if (data != null) {
                        startPhotoZoom(data.getData(), 150);
                    }
                } catch (Exception e) {

                }

                break;
            case PHOTO_CUT:
                try {
                    if (null != data) {
                        setPicToView(data);
                        UpdateUserPortraits(tempFile.getPath());
                    }
                } catch (Exception e) {

                }
                break;

            case USER_NAME:
                if (data != null) {
                    String userName = data.getExtras().getString("userInfoName");
                    tvUserNameValue.setText(userName);
                    UpdateUserInfoData("", userName, "", "", "");

                }
                break;

            case USER_DETAIL_ADRESS:
                if (data != null) {
                    String userAdress = data.getExtras().getString("userInfoAdress");
                    tvUserDetailAdressValue.setText(userAdress);
                    UpdateUserInfoData("", "", "", userAdress, "");

                }

                break;


        }
    }

    //上传用户信息
    private void UpdateUserInfoData(final String logo, final String nickname, String sex, String addr, String birthday) {
        UpdateUserInfoApi userInfoApi = new UpdateUserInfoApi(new HttpOnNextListener<String>() {
            @Override
            public void onNext(String result) {
                MyLog.e("yang", "修改成功");
                PhoneUtils.ShowToastMessage(UserInfoActivity.this, "修改成功");
                //设置环信发送的昵称头像
                if (!StringUtils.isEmpty(logo) && UserHelper.getInstance().getUserInfoModel(UserInfoActivity.this) != null) {
                    UserHelper.getInstance().getUserInfoModel(UserInfoActivity.this).setUserLogo(logo);
                    MessageHelper.getInstance().getUserProfileManager().setCurrentUser(UserHelper.getInstance().getUserInfoModel(UserInfoActivity.this).getNickName(),
                            UserHelper.getInstance().getUserInfoModel(UserInfoActivity.this).getUserLogo());
                } else if (!StringUtils.isEmpty(nickname) && UserHelper.getInstance().getUserInfoModel(UserInfoActivity.this) != null) {
                    UserHelper.getInstance().getUserInfoModel(UserInfoActivity.this).setNickName(nickname);
                    MessageHelper.getInstance().getUserProfileManager().setCurrentUser(UserHelper.getInstance().getUserInfoModel(UserInfoActivity.this).getNickName(),
                            UserHelper.getInstance().getUserInfoModel(UserInfoActivity.this).getUserLogo());
                }

            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                MyLog.e("yang", "错误信息====" + e.getMessage());
                PhoneUtils.ShowToastMessage(UserInfoActivity.this, e.getMessage());
            }
        }, UserInfoActivity.this);
        userInfoApi.setSession(UserHelper.getInstance().getSessionInfoModel(UserInfoActivity.this).getSession());
        userInfoApi.setLogo(logo);
        userInfoApi.setNickName(nickname);
        userInfoApi.setSex(sex);
        userInfoApi.setAddr(addr);
        userInfoApi.setBirthday(birthday);
        HttpManager manager = HttpManager.getInstance();
        manager.doHttpDeal(userInfoApi);
    }


    //上传用户头像
    private void UpdateUserPortraits(String imgUrl) {
        String url = Constants.APP_API_BASE + Constants.RES_UPLOAD;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(UserInfoActivity.this).getSession());
        params.setMultipart(true);
        try {
            params.addBodyParameter("file", new FileInputStream(new File(imgUrl)), "img/jpg", getPhotoFileName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                String data = PhoneUtils.checkResponseFlag(UserInfoActivity.this, result);
                if (data != null) {
                    List<UpLoadUserPortraitModel> list = new Gson().fromJson(data, new TypeToken<List<UpLoadUserPortraitModel>>() {
                    }.getType());
                    for (int i = 0; i < list.size(); i++) {
                        String portraitsUrl = list.get(0).getUrl();
                        UpdateUserInfoData(portraitsUrl, "", "", "", "");

                    }

                }
            }


            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e("update", "onError==" + ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });


    }


    //    适配6.0的动态权限管理
//    打开相机权限和存储权限
    public void onClickAllPermission() {
        Acp.getInstance(this).request(new AcpOptions.Builder()
                        .setPermissions(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .build(),
                new AcpListener() {
                    @Override
                    public void onGranted() {
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        // 指定调用相机拍照后照片的储存路径
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
                        startActivityForResult(intent, PHOTO_CARMERA);
                    }

                    @Override
                    public void onDenied(List<String> permissions) {
                        PhoneUtils.ShowToastMessage(UserInfoActivity.this, permissions.toString() + "权限拒绝");
                    }
                });
    }


    public void onClickWRITE() {
        Acp.getInstance(this).request(new AcpOptions.Builder().setPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE).build(),
                new AcpListener() {
                    @Override
                    public void onGranted() {
                        Intent intent = new Intent(Intent.ACTION_PICK, null);
                        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                        startActivityForResult(intent, PHOTO_PICK);
                    }

                    @Override
                    public void onDenied(List<String> permissions) {
                        PhoneUtils.ShowToastMessage(UserInfoActivity.this, permissions.toString() + "权限拒绝");
                    }
                });
    }

    private void startPhotoZoom(Uri uri, int size) {
        MyLog.e("hep", uri + "");
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");

        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", size);
        intent.putExtra("outputY", size);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PHOTO_CUT);
    }

    // 将进行剪裁后的图片显示到UI界面上
    private void setPicToView(Intent picdata) {
        Bundle bundle = picdata.getExtras();
        if (bundle != null) {
            Bitmap UserPortraitbitmap = bundle.getParcelable("data");
            mRoundimgview.setImageBitmap(UserPortraitbitmap);
            saveCropPic(UserPortraitbitmap);
        }
    }

    // 把裁剪后的图片保存到sdcard上
    private void saveCropPic(Bitmap bmp) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        FileOutputStream fis = null;
        bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
        try {
            fis = new FileOutputStream(tempFile);
            fis.write(baos.toByteArray());
            fis.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != baos) {
                    baos.close();
                }
                if (null != fis) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    //    出生年月
    private int currentYear, currentMonth, currentDay;
    private Dialog mDateDialog;

    private void showDateDialog() {
        int yearIndex = 0, monthIndex = currentMonth - 1, dayIndex = currentDay - 1;
        Calendar tmpCalendar = Calendar.getInstance();
        Date date = null;
        if (!TextUtils.isEmpty(tvUserBirthday.getText())) {
            DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            try {
                date = formatter.parse(tvUserBirthday.getText().toString());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if (date != null) {
                tmpCalendar.setTime(date);
            }
        }
        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display mDisplay = windowManager.getDefaultDisplay();
        mDateDialog = new Dialog(UserInfoActivity.this, R.style.AlertDialogStyle);
        View dialogView = LayoutInflater.from(UserInfoActivity.this).inflate(R.layout.dialog_archive_add_date, null);
        Button btnCancel = (Button) dialogView.findViewById(R.id.btn_cancel);
        Button btnSure = (Button) dialogView.findViewById(R.id.btn_sure);

        final WheelView wvYear, wvMonth, wvDay;
        wvYear = (WheelView) dialogView.findViewById(R.id.wv_archive_date_year);
        wvMonth = (WheelView) dialogView.findViewById(R.id.wv_archive_date_month);
        wvDay = (WheelView) dialogView.findViewById(R.id.wv_archive_date_day);

        final String[] yearArray = new String[100];
        for (int i = currentYear; i > currentYear - 100; i--) {
            yearArray[currentYear - i] = "" + i + "年";
            if (date != null && tmpCalendar.get(Calendar.YEAR) == i) {
                yearIndex = currentYear - i;
            }
        }
        ArrayWheelAdapter<String> yearAdapter = new ArrayWheelAdapter<String>(this, yearArray);
        yearAdapter.setTextSize(20);
        wvYear.setViewAdapter(yearAdapter);
        wvYear.setCurrentItem(yearIndex);
        wvYear.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(WheelView wheel) {

            }

            @Override
            public void onScrollingFinished(WheelView wheel) {

                int tmpIndex = wvDay.getCurrentItem();
                int tmpDayOfMonth = getDayOfMonth(Integer.parseInt(yearArray[wvYear.getCurrentItem()].replace("年", "")), wvMonth.getCurrentItem() + 1);
                String[] tmpDayArray = new String[tmpDayOfMonth];
                for (int k = 0; k < tmpDayOfMonth; k++) {
                    tmpDayArray[k] = "" + (k + 1) + "日";
                }
                if (tmpIndex >= tmpDayOfMonth) {
                    tmpIndex = tmpDayOfMonth - 1;
                }
                ArrayWheelAdapter<String> dayAdapter = new ArrayWheelAdapter<String>(UserInfoActivity.this, tmpDayArray);
                dayAdapter.setTextSize(20);
                wvDay.setViewAdapter(dayAdapter);
                wvDay.setCurrentItem(tmpIndex);
            }
        });

        final String[] monthArray = new String[12];
        for (int j = 0; j < 12; j++) {
            monthArray[j] = "" + (j + 1) + "月";
            if (date != null && tmpCalendar.get(Calendar.MONTH) == j) {
                monthIndex = j;
            }
        }
        ArrayWheelAdapter<String> monthAdapter = new ArrayWheelAdapter<String>(this, monthArray);
        monthAdapter.setTextSize(20);
        wvMonth.setViewAdapter(monthAdapter);
        wvMonth.setCurrentItem(monthIndex);
        wvMonth.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(WheelView wheel) {
            }

            @Override
            public void onScrollingFinished(WheelView wheel) {
                int tmpIndex = wvDay.getCurrentItem();
                int tmpDayOfMonth = getDayOfMonth(Integer.parseInt(yearArray[wvYear.getCurrentItem()].replace("年", "")), wvMonth.getCurrentItem() + 1);
                String[] tmpDayArray = new String[tmpDayOfMonth];
                for (int k = 0; k < tmpDayOfMonth; k++) {
                    tmpDayArray[k] = "" + (k + 1) + "日";
                }
                if (tmpIndex >= tmpDayOfMonth) {
                    tmpIndex = tmpDayOfMonth - 1;
                }
                ArrayWheelAdapter<String> dayAdapter = new ArrayWheelAdapter<String>(UserInfoActivity.this, tmpDayArray);
                dayAdapter.setTextSize(20);
                wvDay.setViewAdapter(dayAdapter);
                wvDay.setCurrentItem(tmpIndex);
            }
        });

        int dayOfMonth = getDayOfMonth(Integer.parseInt(yearArray[yearIndex].replace("年", "")), monthIndex + 1);
        final String[] dayArray = new String[dayOfMonth];
        for (int k = 0; k < dayOfMonth; k++) {
            dayArray[k] = "" + (k + 1) + "日";
            if (date != null && tmpCalendar.get(Calendar.DATE) == k + 1) {
                dayIndex = k;
            }
        }
        ArrayWheelAdapter<String> dayAdapter = new ArrayWheelAdapter<String>(this, dayArray);
        dayAdapter.setTextSize(20);
        wvDay.setViewAdapter(dayAdapter);
        wvDay.setCurrentItem(dayIndex);
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDateDialog.dismiss();
            }
        });
        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String txtYear = yearArray[wvYear.getCurrentItem()].replace("年", ""),
                        txtMonth = "0" + (wvMonth.getCurrentItem() + 1),
                        txtDay = "0" + (wvDay.getCurrentItem() + 1);
                txtMonth = txtMonth.substring(txtMonth.length() - 2);
                txtDay = txtDay.substring(txtDay.length() - 2);
                String birthday = txtYear + "-" + txtMonth + "-" + txtDay;
//                MyLog.e("yang","选择时间=="+TimeUtils.getTimeStamp(birthday,"yyyy-MM-dd")+"");
//                MyLog.e("yang","系统时间=="+TimeUtils.getTimeStamp(TimeUtils.formatTimeDifference3(System.currentTimeMillis()),"yyyy-MM-dd"));
                if (TimeUtils.getTimeStamp(birthday, "yyyy-MM-dd") > TimeUtils.getTimeStamp(TimeUtils.formatTimeDifference3(System.currentTimeMillis()), "yyyy-MM-dd")) {
                    PhoneUtils.ShowToastMessage(UserInfoActivity.this, "请选择正确的日期");
                } else {
                    tvUserBirthday.setText(birthday);
                    UpdateUserInfoData("", "", "", "", timeMilliSecond(birthday) + "");
                    mDateDialog.dismiss();
                }

            }
        });
        mDateDialog.setContentView(dialogView);
        mDateDialog.setCancelable(true);
        mDateDialog.setCanceledOnTouchOutside(true);

        Window dialogWindow = mDateDialog.getWindow();
        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        p.width = (int) (mDisplay.getWidth() * 0.86);
        dialogWindow.setAttributes(p);
        mDateDialog.show();
    }


    private int getDayOfMonth(int year, int month) {
        Calendar c = Calendar.getInstance();
        c.set(year, month, 0);
        return c.get(Calendar.DAY_OF_MONTH);
    }

    private long timeMilliSecond(String orderTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return sdf.parse(orderTime).getTime();
        } catch (Exception e) {

        }
        return 0;
    }
}
